<?php
// +----------------------------------------------------------------------
// |     【PurchaseMain】Controller 控制器
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\admin\controller\purchase;

use think\facade\Request;
use app\common\service\PurchaseMain as S;
use app\common\model\PurchaseMain as M;
use app\common\model\PurchaseInfo as INFO_M;
use app\common\model\FabricMain as Fabric;
use app\common\model\FabricColor as Color;
use app\common\model\StaffMain as Staff;
use app\common\service\PurchaseInfo as INFO_S;
use app\common\service\AiService as AI;
use app\common\model\SystemConfig as CONFIG;

class Main extends  \app\admin\controller\Base
{
    protected $middleware = ['AdminCheck','AdminPermission'];
    private $maxlist=15;                    //默认最高行数

	//初始化
	public function initialize(){
		parent::initialize();
		
		$this->assign('controller_title','采购管理');
	}

    // 列表
    public function index(){
        if (Request::isAjax()) {
            return $this->getJson(M::getList());
        }
        
        $year = I("year",0);
        $month = I("month",0);
        $day = I("day",0);
        
        $old_year=M::order('create_time asc')->value('create_time');
        $old_year=$old_year!=''?date('Y',$old_year):date('Y');
        
        return $this->fetch('',[
            "old_year" => $old_year,
            'year'=>$year,
            'month'=>$month,
            'day'=>$day,
            'options'=>config_cache_file('options'),
        ]);
    }
    
    // 添加
    public function add(){
        if (Request::isAjax()) {
            $post=Request::post();
            if(!isset($post['staff_id']) || intval($post['staff_id'])<=0){
                return $this->getJson(
                    ['msg'=>'请先选择下单员工','code'=>201]
                );
            }else if($post['info']['fabric_code'][0]==''){
                return $this->getJson(
                    ['msg'=>'请完善采购信息','code'=>201]
                );
            }
            $result=S::goAdd($post,true);
        	//判断是否添加成功
        	if(array_key_exists('code',$result)){
        		return $this->getJson($result);
        	}else{
        		INFO_S::write_info($result['info'],$result['id']);
                INFO_S::upPurchaseText($result['id']);
        		return $this->getJson();
        	}
        }

        return $this->fetch('edit',[
			'action_up'=>false,
            'options'=>config_cache_file('options'),
            'staff_list'=>Staff::listData(['user_type'=>1],'sort asc'),
            'maxlist'=>I('get.maxlist',$this->maxlist,'intval'),
		]);
    }

    // 编辑
    public function edit($id){
        if (Request::isAjax()) {
            $result=S::goEdit(Request::post(),['id'=>$id]);
            //判断是否修改成功
            if(array_key_exists('code',$result)){
            	return $this->getJson($result);
            }else{
                $info=I('post.info');
            	INFO_S::write_info($info,$id);
                INFO_S::upPurchaseText($id);
            	return $this->getJson();
            }
        }
		
		$maxlist=I('get.maxlist',0,'intval');
		$model=M::info($id);
        
		if($model!=''){
			$Tinfo=INFO_M::listData($id,[],'id asc');
			if($maxlist==0){
				if(count($Tinfo)>=$this->maxlist){
					$maxlist=count($Tinfo)+5;
				}else{
					$maxlist=$this->maxlist;
				}
			}
            $staff_name=Staff::where('id='.$model['staff_id'])->value('name');
			return $this->fetch('',[
				'action_up'=>true,
				'model' => $model,
				'Tinfo'=>$Tinfo,
                'staff_name'=> $staff_name,
                'staff_list'=>Staff::listData(['user_type'=>1],'sort asc'),
				'maxlist'=>$maxlist,
				'options'=>config_cache_file('options'),
			]);
		}else{
			$this->getJson(1202);	
		}
    }
    
    // 采购明细
    public function info($id){    	
    	$maxlist=I('get.maxlist',0,'intval');
    	$T=M::info($id);
    	if($T!=''){
    		$Tinfo=INFO_M::listData($id,[],'id asc');
            // print_r($Tinfo);
    		if($maxlist==0){
    			if(count($Tinfo)>=$this->maxlist){
    				$maxlist=count($Tinfo)+5;
    			}else{
    				$maxlist=$this->maxlist;
    			}
    		}
            $staff_name=Staff::where('id='.$T['staff_id'])->value('name');
    		return $this->fetch('',[
    			'T' => $T,
    			'Tinfo'=>$Tinfo,
                'staff_name'=> $staff_name,
    			'maxlist'=>$maxlist,
    			'options'=>config_cache_file('options'),
    		]);
    	}else{
    		$this->getJson(1202);	
    	}
    }
    
    // 采购打印
    public function prints(){
        $ids = I('get.ids', '');
        $ids = explode('|', $ids);
        // 数组去重
        $ids = array_unique($ids);
        
        if (count($ids) <= 0) {
            return $this->getJson(1202);
        }
    
        // 获取所有记录
        $T = M::whereIn('id', $ids)->select();
        
        // 检查所有记录的staff_id是否相同
        $staffIds = $T->column('staff_id');
        if (count(array_unique($staffIds)) > 1) {
            return $this->error('合并打印销售员必须是同个人！','');
        }
    
        // 获取第一条记录的staff_id（此时所有记录staff_id相同）
        $firstStaffId = $T[0]['staff_id'];
        
        $Tinfo = INFO_M::listData($ids, [['unit','<>','条']], 'id asc');
        
        if(!$Tinfo) return $this->error('没有版布记录！','');
        
        $staff = Staff::find($firstStaffId);
        
        //第一条才够数据
        $Tdata=$T[0];
        $Tdata['staff']=$staff;
        
        $print=CONFIG::get('info.print');

        //获取打印格式数据
        $print_data=M::labelPrintData($Tdata,$Tinfo,$print);
        
        return $this->fetch('', [
            'Tinfo' => $Tinfo,
            'staff' => $staff,
            'print'=>$print,
            'print_data'=>json_encode($print_data),
            'options' => config_cache_file('options'),
        ]);
    }
    
    //AI识别采购信息
    public function ai_read_info(){
        $text=I('post.text','');
        $res=AI::readPurchaseInfo($text);
        return $this->getJson($res,true);        
    }
    
    //动态加载产品列表数据
    public function fabric(){
    	if(Request::isAjax()){
    		$data=F('fabric_list');
    		if($data==''){
                $filed=[
                    'f.id',
                    'f.fabric_code',
                    'f.fabric_name',
                    'f.sup_code',
                    'f.sup_empty',
                    'f.is_change',
                    'f.markup',
                    'f.sup_id',
                    's.sup_name ',
                    's.exp_method',
                    's.cut_payment',
                    's.bulk_payment',
                    's.exp_name',
                ];
    			$Fabric=Fabric::allList($filed);
    			$Fabric=set_key($Fabric,'fabric_code');
    			$data=$Fabric;
    			F('fabric_list',serialize($Fabric));
    		}else{
    			$data=unserialize($data);
    		}
    		return json($data);
    	}else{
    		$this->error('参数有误！');
    	}
    }
    
    //动态加载产品列表数据
    public function color() {
        if (Request::isAjax()) {
            $id = I('post.id', 0, 'intval');
            $color_code = I('post.color', 0, 'intval');
    
            $color = Color::alias('c')
                ->leftJoin('supplier_main s','c.sup_id = s.id')
                ->field('c.*,s.sup_name,s.exp_method,s.exp_name')
                ->where([
                    'c.fabric_id' => $id,
                    'c.color_code' => $color_code
                ])
                ->find();
    
            return json($color ?? null);
        }
        $this->error('非法请求！');
    }

    // 状态
    public function status($id){
        $type=I('type','');
        if($type=='info'){
            return $this->getJson(INFO_S::goStatus(Request::post(),$id));
        }else if($type=='more_status'){
            // 传递的是多ID的   1|2|3
            $status=I('status');
            $ids=explode('|',$id);
            
            //如果订单完成，默认完成打印凭证
            if($status==99){
                $proof=1;
            }else{
                $proof=0;
            }
            //更新打印状态
            INFO_M::whereIn('pur_id',$ids)->update(['proof'=>$proof]);
            M::whereIn('id',$ids)->update(['status'=>$status]);
            return $this->getJson(['msg' => '操作成功', 'code' => 200]);
        }else{
            return $this->getJson(S::goStatus(Request::post(),$id));    
        }
    }

    // 删除
    public function remove($id){
        return $this->getJson(S::goRemove($id));
    }

    // 批量删除
    public function batchRemove(){
        return $this->getJson(S::goBatchRemove(Request::post('ids')));
    }

    // 回收站
    public function recycle(){
        if (Request::isAjax()) {
            return $this->getJson(S::goRecycle());
        }
        return $this->fetch();
    }
	
    // 设置某个值
    public function setValue(){
        if (Request::isAjax()) {
            $type=I('type','');
            if($type=='info'){
                return $this->getJson(INFO_S::setFieldValue(Request::post()));
            }else{   
                return $this->getJson(S::setFieldValue(Request::post()));
            }
        }
        return $this->fetch();
    }
}
